﻿using KafkaUtil;
using KafkaUtil.Integration;
using Maikebing.Data.Taos;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Hosting;
using NewLife.Caching;
using NewLife.Collections;
using NewLife.Log;
using PtlSave.Model;
using PtlSave.Util;
using System;
using System.IO;
using System.Threading;

namespace PtlSave
{
    class Program
    {
        static void Main(string[] args)
        {
            XTrace.UseConsole();
            XTrace.WriteLine("load config.json ...");
            //读取配置文件
            _configuration = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "cfg/config.json", ReloadOnChange = true }).Build();
            XTrace.WriteLine("Save Server Start...");
            //PtlSave();
            new Thread(PtlSave).Start();

            Thread.Sleep(Timeout.InfiniteTimeSpan);
        }

        /*
         * 入口
         */
        private static IConfiguration _configuration;
        public static DataBaseInit _dataBaseInit;
        public static DataDeal _dataDeal;

        private static void PtlSave()
        {
            //kafka服务地址
            string[] hosts = new string[] { _configuration.GetSection("KafkaSettings").GetSection("BootstrapServers").Value };
            //消费者配置
            KafkaConsumerOptions consumerOptions = new KafkaConsumerOptions
            {
                BootstrapServers = hosts,
                EnableAutoCommit = true,
                GroupId = _configuration.GetSection("KafkaSettings").GetSection("GroupId").Value,
                Subscribers = new KafkaSubscriber[] { new KafkaSubscriber() { Topic = _configuration.GetSection("KafkaSettings").GetSection("Topic").Value } }
            };

            //涛思数据库连接参数串
            TaosConnectionStringBuilder builder = new TaosConnectionStringBuilder()
            {
                DataSource = _configuration.GetSection("TaosSettings").GetSection("DataSource").Value,
                DataBase = _configuration.GetSection("TaosSettings").GetSection("DataBase").Value,
                Username = _configuration.GetSection("TaosSettings").GetSection("Username").Value,
                Password = _configuration.GetSection("TaosSettings").GetSection("Password").Value,
                Port = 6030
            };

            //MySQL数据库连接串
            // "Data Source=server;Database=mydb;User ID=username;Password=pwd;Command Logging=false";
            string connectionString = _configuration.GetSection("MySQLSettings").GetSection("ConnString").Value;
            //MySQL数据库版本
            string version = _configuration.GetSection("MySQLSettings").GetSection("Version").Value;// "5.7.17";

            //数据库初始化
            _dataBaseInit = new DataBaseInit(builder, connectionString, version);

            if (!_dataBaseInit.mysqlConn || !_dataBaseInit.taosConn)
            {
                XTrace.WriteLine("mysql or taos connect error, service failed to start");
                return;
            }

            //数据处理，保存
            _dataDeal = new DataDeal(consumerOptions, builder);

            int GrpcPort = CommonUtil.IsInt(_configuration.GetSection("GrpcPort").Value) ? int.Parse(_configuration.GetSection("GrpcPort").Value) : 5005;
            new Thread((ThreadStart)delegate { StartGrpc(GrpcPort); }).Start();
        }

        private static void StartGrpc(int port)
        {
            XTrace.WriteLine("GRPC服务启动");
            //开启GRPC服务
            CreateHostBuilder(new string[] { port.ToString() }).Build().Run();
        }

        /*
         * 开启GRPC服务
         */
        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    int port = int.Parse(args[0]);
                    webBuilder.UseStartup<GRPCStartup>()
                    .UseKestrel(opt => { })
                    .ConfigureAppConfiguration((builderContext, config) =>
                    {
                        config.AddJsonFile("appsettings.json", optional: false);    //加载配置文件
                    })
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseUrls("http://*:" + port.ToString() + ";https://*:" + (port + 1).ToString());
                });

    }
}
